package com.innover.controller;

import com.innover.domain.FileInfo;
import com.innover.domain.FileList;
import com.innover.service.FileInfoService;
import com.innover.util.AppFolders;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Controller
@RequestMapping("/admin")
public class FileController{ // 实现ServletContextAware接口，获取本地路径
    Logger LOGGER = LoggerFactory.getLogger("FileController");

    @Autowired
    @Qualifier("fileInfoService")
    private FileInfoService fileInfoService;

    //跳转到上传页面
    @RequestMapping(value = "/uploadpage")
    public String goToUploadPage() {
        return "upload_page";
    }

    @RequestMapping(value = "/songupload", method = RequestMethod.POST)
    // 将文件上传请求映射到该方法
    @ResponseBody
    public String handleFormUpload(HttpServletRequest request,@RequestParam("myfile") CommonsMultipartFile mFile,@RequestParam("weekly") boolean weekly) throws FileNotFoundException { // 请求参数一定要与form中的参数名对应
        System.out.println("name:"+System.currentTimeMillis());
        if (null != mFile) {
                System.out.println("myFile:" + mFile.toString());
                String path = request.getSession().getServletContext().getRealPath(AppFolders.UPLOAD_SONG_FOLDER); // 获取本地存储路径// WebUtils.getRealPath(servletContext,"/"+user.getUsername()+"/"); //
                File folder = new File(path);
                if (!folder.exists()) {
                    folder.mkdirs();
                }
                String fileSuffix=getFileSuffix(mFile.getFileItem().getName());
                String filenameInDB= UUID.randomUUID()+"_"+System.currentTimeMillis()+fileSuffix;
                File file = new File(path, filenameInDB); // 新建一个文件
                try {
                    mFile.getFileItem().write(file); // 将上传的文件写入新建的文件中
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setFileName(mFile.getFileItem().getName());
                    fileInfo.setFilePath(file.getAbsolutePath());
                    fileInfo.setWeekly(weekly?1:0);
                    fileInfo.setUploadDate(new Date());
                    System.out.println(fileInfo.toString());
                    LOGGER.info(fileInfo.toString());
                    fileInfoService.editSave(fileInfo);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            return "Successed";// 返回成功视图
        } else {
            return "Failed"; // 返回失败视图
        }
    }
    private String getFileSuffix(String filename){
        return filename.substring(filename.lastIndexOf("."),filename.length());
    }
    @RequestMapping (value="/listfiles")
    public ModelAndView listFile(ModelMap modelMap){
        List filelist=fileInfoService.queryAll(" from FileInfo");
        LOGGER.debug(filelist.toString());
        modelMap.addAttribute("filelist",filelist);
        return new ModelAndView("file_list",modelMap);
    }

    @RequestMapping(value="/delFile/{id}")
    public String deleteFile(@PathVariable int id){
        fileInfoService.deleteFile(id);
        return "redirect:/listfiles";
    }

    @RequestMapping(value = "/filepage")
    public ModelAndView ajaxListFile(@RequestParam("page") Long page, @RequestParam("rows") int rows){
        FileList fileList = new FileList();

        Long count = fileInfoService.countAll(FileInfo.class);
        fileList.setRecords(count);
        fileList.setPage(page);
        Long total = 0l;
        if(count%rows==0){
            total = count/rows;
        }else {
            total = count/rows+1;
        }

        fileList.setTotal(total);
        List ft=fileInfoService.listAll(FileInfo.class,page.intValue(),rows);
        fileList.setRows(ft);
        ModelAndView mav = new ModelAndView("defaultJsonView");
        mav.addObject(fileList);
        return mav;
    }

    @RequestMapping(value = "/del")
    @ResponseBody
    public  String ajaxDelFile(@RequestParam("oper") String oper,@RequestParam("id") String id){

        if(!StringUtils.isEmpty(oper)&&!StringUtils.isEmpty(id)){
//            String hsql = "delete from FileInfo where id in" +"("+id+")" ;
//            fileInfoService.delete(hsql);
            fileInfoService.deleteFile(id);

        }

        return id;
    }

//    @RequestMapping(value = "/download")
//    public ModelAndView downloadFile(@RequestParam("id") Integer id, HttpServletRequest request, HttpServletResponse response ) throws IOException {
//
//        response.setContentType("text/html;charset=utf-8");
//        request.setCharacterEncoding("UTF-8");
//        java.io.BufferedInputStream bis = null;
//        java.io.BufferedOutputStream bos = null;
//
//        FileInfo fileInfo = fileInfoService.get(FileInfo.class, id);
//
//
//        String downLoadPath = fileInfo.getFilePath();
//
//        String  fileName = fileInfo.getFileName();
//        try {
//            long fileLength = new File(downLoadPath).length();
//            response.setContentType("application/x-msdownload;");
//            response.setHeader("Content-disposition", "attachment; filename="
//                    + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
//            response.setHeader("Content-Length", String.valueOf(fileLength));
//            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
//            bos = new BufferedOutputStream(response.getOutputStream());
//            byte[] buff = new byte[2048];
//            int bytesRead;
//            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
//                bos.write(buff, 0, bytesRead);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (bis != null)
//                bis.close();
//            if (bos != null)
//                bos.close();
//        }
//
//        return null;
//    }

}